package com.daisuxia.back.controller;

import java.util.HashMap;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daisuxia.back.service.IBackUserService;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.util.SendSmsUtil;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

import redis.clients.jedis.JedisCluster;

/**
 * 
 * 类描述：后台登录类 <br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-6-28 下午02:57:46 <br>
 * 
 * @version
 * 
 */
@Controller
public class LoginController extends BaseController {
	public static final String PROCESS_URL = "processUrl";
	public static final String RETURN_URL = "returnUrl";
	private static Logger logger = Logger.getLogger(LoginController.class);
	public final static String SMS_SEND_IN_ONE_MINUTE = "SMS_SEND_IN_ONE_MINUTE_";// Redis某个手机号1分钟内已发送验证码key前缀
	public final static String SMS_REGISTER_PREFIX = "newPhoneCode_";// Redis注册key前缀
	public final static int INFECTIVE_SMS_TIME = 300;// 短信默认有效时间300秒
	@Autowired
	private IBackUserService backUserService;
	@Autowired
	JedisCluster jedisCluster;

	/**
	 * 获得地址
	 * 
	 * @param processUrl
	 * @param returnUrl
	 * @param authId
	 * @return
	 */
	private String getView(String processUrl, String returnUrl) {
		if (!StringUtils.isBlank(processUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(processUrl);
			if (!StringUtils.isBlank(returnUrl)) {
				sb.append("?").append(RETURN_URL).append("=").append(returnUrl);
			}
			return sb.toString();
		} else if (!StringUtils.isBlank(returnUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(returnUrl);

			return sb.toString();
		} else {
			return null;
		}
	}

	@RequestMapping(value = "/err", method = RequestMethod.GET)
	public String err(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "err";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

		try {
			String processUrl = request.getParameter(PROCESS_URL);
			String returnUrl = request.getParameter(RETURN_URL);
			String message = request.getParameter(MESSAGE);
			BackUser backUser = (BackUser) request.getSession().getAttribute(Constant.BACK_USER);
			if (backUser != null) {
				String view = getView(processUrl, returnUrl);
				if (view != null) {
					return view;
				} else {

					return "index";
				}
			}
			if (!StringUtils.isBlank(processUrl)) {
				model.addAttribute(PROCESS_URL, processUrl);
			}
			if (!StringUtils.isBlank(returnUrl)) {
				model.addAttribute(RETURN_URL, returnUrl);
			}
			if (!StringUtils.isBlank(message)) {
				model.addAttribute(MESSAGE, message);
			}
		} catch (Exception e) {
			logger.error("back login error ", e);
		}
		return "login";
	}

	@RequestMapping(value = "/sendSmsBack", method = RequestMethod.POST)
	public void sendSmsBack(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		ServiceResult serviceResult = new ServiceResult("500", "未知异常");
		try {
			if (validateSubmit(request, response)) {
				params.put("status", BackUser.STATUS_USE);
				BackUser backUser = backUserService.findOneUser(params);
				if (backUser != null) {
					Object tmpPwd = params.get("userPassword");
					if (tmpPwd != null) {
						AESUtil aesEncrypt = new AESUtil();
						if (backUser.getUserPassword().equals(MD5coding.MD5(aesEncrypt.encrypt(tmpPwd.toString(), "")))) {
							String userPhone = backUser.getUserMobile();
							String hasSendOneMinKey = SMS_SEND_IN_ONE_MINUTE + userPhone;
							if (jedisCluster.get(hasSendOneMinKey) != null) {
								serviceResult.setMsg("请一分钟后再尝试发送");
							} else {
								String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
								if (SendSmsUtil.sendSmsCL(userPhone, rand)) {
									jedisCluster.setex(hasSendOneMinKey, 60, userPhone);
									// 存入redis
									jedisCluster.setex(SMS_REGISTER_PREFIX + userPhone, INFECTIVE_SMS_TIME, rand);
									serviceResult = new ServiceResult(ServiceResult.SUCCESS, "发送成功！");
								} else {
									serviceResult.setMsg("短信发送失败,请联系技术！");
								}
							}

						} else {
							serviceResult.setMsg("登录密码错误！");
						}
					} else {
						serviceResult.setMsg("密码不能为空！");
					}
				} else {
					serviceResult.setMsg("该用户不存在！");
				}
			} else {
				serviceResult.setMsg("图形验证码错误");
			}
		} catch (Exception e) {
			logger.error("sendSmsBack error params=" + params, e);
		}
		SpringUtils.renderJson(response, serviceResult);
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String submit(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		String errMsg = null;
		String userPhone = params.get("userMobile") + "";
		String key = SMS_REGISTER_PREFIX + userPhone;
		try {
			String smsCode = params.get("smsCode") + "";
			String code = jedisCluster.get(key);
			if (code != null) {
				if (code.equals(smsCode)) {
					params.put("status", BackUser.STATUS_USE);
					BackUser backUser = backUserService.findOneUser(params);
					if (backUser != null) {
						AESUtil aesEncrypt = new AESUtil();
						Object tmpPwd = params.get("userPassword");
						if (backUser.getUserPassword().equals(MD5coding.MD5(aesEncrypt.encrypt(tmpPwd.toString(), "")))) {
							request.getSession(true).setAttribute(Constant.BACK_USER, backUser);
							request.getSession().setMaxInactiveInterval(60 * 60 * 6);
							jedisCluster.del(key);
						} else {
							errMsg = "密码错误！";
						}
					} else {
						errMsg = "该用户不存在！";
					}
				}
			else {
					errMsg = "短信验证码错误！";
				}
			} else {
				errMsg = "验证码失效或不存在！";
			}
		} catch (Exception e) {
			jedisCluster.del(key);
			errMsg = "服务器异常，稍后重试！";
			logger.error("post login error params=" + params, e);
		}
		if (errMsg != null) {
			model.addAttribute(MESSAGE, errMsg);
			return "login";
		} else {
			return "redirect:indexBack";
		}
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		// backloginOut(request);
		request.getSession().removeAttribute(Constant.BACK_USER);
		return "redirect:login";
	}
}
